# -*- coding:utf-8 -*-

"""
    客户端下载zip更新统计
"""


import tornado.web
from utils.routes import route
from utils import log as logger
from utils import mongo
from configure import config



@route('/update/count?', 'update.count')
class CountHandler(tornado.web.RequestHandler):
    """ 客户端下载zip更新统计
    """
    db_name = config.DB_NAME
    collection_name = config.COLLECTION_DATAS

    @tornado.web.asynchronous
    @tornado.gen.engine
    def get(self, *argl, **argd):
        scope = self.get_argument('scope', None)
        sn_id = self.get_argument('sn_id', None)
        ver = self.get_argument('ver', None)
        update_success = self.get_argument('update_success', None)
        logger.info('scope:', scope, 'sn_id:', sn_id, 'ver:', ver, 'update_success:', update_success, caller=self)

        if not sn_id or not ver or not scope or update_success not in ['0', '1']:
            results = {'code': 1, 'info': 'params error!'}
            self.finish(results)
            return

        sn_id_6 = sn_id[:6]   # 取前6位
        spec = {
            'sn_ids':       {'$in': [sn_id_6]}, # 校验sn_id
            'ver':          ver,
            'scope':        scope
        }
        r = yield tornado.gen.Task(mongo.find_one, self.db_name, self.collection_name, spec)
        if r:
            if update_success == '0':
                update_failed = r.get('update_failed', 0) + 1
                yield tornado.gen.Task(mongo.update, self.db_name, self.collection_name, spec,
                                       {'update_failed': update_failed})
            else:
                update_success = r.get('update_success', 0) + 1
                yield tornado.gen.Task(mongo.update, self.db_name, self.collection_name, spec,
                                       {'update_success': update_success})
            results = {'code':      0,
                       'result':    {
                           'sn_id':           sn_id,
                           'ver':             ver,
                           'update_success':  update_success,
                           'scope':           scope
                       }}
        else:
            results = {
                'code': 2,
                'info': "could't find the package info."
            }

        self.finish(results)
        logger.debug('do response:', results, caller=self)


    def post(self, *argl, **argd):
        self.get(*argl, **argd)
        
